var app = getApp();
const util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    movies: {},
    navigationBarTitle:"",
    requestUrl:"",
    totalCount:0,
    isF: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var cetegory = options.cetegory;
    this.data.navigationBarTitle=cetegory;

    var doubanurl = app.globalData.doubanurl;
    var url='';
    switch(cetegory){
        case '正在热映':
        url = doubanurl +'/v2/movie/in_theaters';
        break;
        case '即将上映':
        url = doubanurl + '/v2/movie/coming_soon';
        break;
        case 'top250':
        url = doubanurl + '/v2/movie/top250';
        break;
    }
    this.setData({ requestUrl: url });
    util.http(url, this.porcessDoubanData);
  },
  onReachBottom: function (event) {
    var newUrl = this.data.requestUrl + '?start=' + this.data.totalCount + '&count=20';
    util.http(newUrl, this.porcessDoubanData);
    wx.showNavigationBarLoading();
  },

  porcessDoubanData: function (doubanData){
    console.log(doubanData);
    var movies = [];
    for (var ids in doubanData.subjects) {
      var subject = doubanData.subjects[ids];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...';
      }
      var temp = {
        title: title,
        average: subject.rating.average,
        stars: util.convertToStarsArray(subject.rating.stars),
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp);
    }
    var totalMovies = [];
    if (!this.data.isF){
      totalMovies = this.data.movies.concat(movies);
    }else{
      totalMovies = movies;
      this.data.isF=false;
    }
  
    this.setData({ movies: totalMovies});
    this.data.totalCount += 20;
    wx.hideNavigationBarLoading();
  },

  onMovieTap: function (event) {

    var movieId = event.currentTarget.dataset.movieid;
    console.log(movieId);
    wx.navigateTo({
      url: '../movie-detail/movie-detail?movieId=' + movieId,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.setNavigationBarTitle({
      title: this.data.navigationBarTitle
    })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var newUrl = this.data.requestUrl + '?start=0&count=20';
    this.data.movies=[];
    this.data.isF=true;
    this.data.totalCount=0;
    util.http(newUrl, this.porcessDoubanData);
    wx.showNavigationBarLoading();

  },

  /**
   * 页面上拉触底事件的处理函数
   */

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})